<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" :rules="queryForm" v-show="showSearch"
             label-width="88px">
      <el-form-item label="会议室名称" prop="broadroomName">
        <el-input
          v-model="queryParams.broadroomName"
          placeholder="请输入会议室名称"
          clearable
          size="small"
          maxlength="30"
          show-word-limit
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会议室地址" prop="broadroomAddress">
        <el-input
          v-model="queryParams.broadroomAddress"
          placeholder="请输入会议室地址"
          clearable
          size="small"
          maxlength="30"
          show-word-limit
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会议室开放状态" prop="broadroomStatus" label-width="120">
        <el-select v-model="queryParams.broadroomStatus" placeholder="会议室开放状态" clearable size="small"
                   style="width: 140px">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择时间段" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="info" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['server:broadroom:add']"
        >新增
        </el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          v-hasPermi="['server:broadroom:remove']"
        >删除
        </el-button>
        <el-button
          type="info"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['server:broadroom:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>


    <el-table v-loading="loading" :data="broadroomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" width="90" align="center" type="index" prop="broadroomId" key="broadroomId"
                       v-if="columns[0].visible"/>
      <!--      <el-table-column label="会议室编号" align="center" prop="broadroomId" key="broadroomId" v-if="columns[0].visible"/>-->
      <el-table-column label="会议室名称" align="center" key="broadroomName" prop="broadroomName" v-if="columns[1].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="会议室地址" align="center" key="broadroomAddress" prop="broadroomAddress"
                       v-if="columns[2].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="会议室人数" align="center" key="broadroomNum" prop="broadroomNum" v-if="columns[3].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="会议室开放状态" align="center" key="broadroomStatus" prop="broadroomStatus"
                       :formatter="statusFormat" v-if="columns[4].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="创建时间" align="center" key="createTime" prop="createTime" width="180"
                       v-if="columns[5].visible"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['server:broadroom:edit']"
          >修改
          </el-button>
          <el-button
            :disabled="scope.row.broadroomStatus==0?false:true"
            size="mini"
            type="text"
            icon="el-icon-time"
            @click="handleUpdateStatus(scope.row)"
            v-hasPermi="['server:broadroom:book']"
          >预约
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['server:broadroom:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改会议室信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="会议室名称" prop="broadroomName" maxlength="30">
          <el-input v-model="form.broadroomName" placeholder="请输入会议室名称" maxlength="30"/>
        </el-form-item>
        <el-form-item label="会议室地址" prop="broadroomAddress">
          <el-input v-model="form.broadroomAddress" placeholder="请输入会议室地址" maxlength="30"/>
        </el-form-item>
        <el-form-item label="会议室人数" prop="broadroomNum">
          <el-input v-model="form.broadroomNum" type="number" placeholder="请输入会议室人数" maxlength="5"/>
        </el-form-item>
        <el-form-item label="会议室开放状态">
          <el-select v-model="form.broadroomStatus" placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="200"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 预定会议室 -->
    <el-dialog :title="title" :visible.sync="book" width="500px" append-to-body :destroy-on-close="true">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="会议室名称" prop="broadroomName">
          <el-input v-model="form.broadroomName" placeholder="请输入会议室名称" disabled/>
        </el-form-item>
        <el-form-item label="会议室地址" prop="broadroomAddress">
          <el-input v-model="form.broadroomAddress" placeholder="请输入会议室地址" disabled/>
        </el-form-item>
        <el-form-item label="企业名称" prop="compName">
          <el-select v-model="form.compName"
                     style="width: 100%"
                     filterable
                     placeholder="请输入企业名称"
                     remote
                     clearable
                     reserve-keyword
                     @change="changeName"
                     :remote-method="Tolikesearch">
            <el-option
              v-for="item in compOptions"
              :key="item.compId"
              :label="item.compName"
              :value="item.compName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人号码" prop="phoneNumber">
          <el-select v-model="form.phoneNumber"
                     style="width: 100%;"
                     filterable
                     placeholder="请输入联系人号码"
                     remote
                     clearable
                     reserve-keyword
                     @change="changePhone"
                     :remote-method="phoneSearch">
            <el-option
              v-for="item in userOptions"
              :key="item.staffId"
              :label="item.staffPhone"
              :value="item.staffPhone">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入联系人姓名"/>
        </el-form-item>
        <el-form-item label="预约时间段" prop="date">
          <el-date-picker
            style="width: 100%;"
            v-model="form.date"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            @change="selectedDate"
          >
          </el-date-picker>
          <div class="timesList">
            <div
              v-for="item in timeList"
              :label="item"
              :key="item"
              :ref="item"
              clearable
              class="times"
              @click="selectTime(item)">{{ item }}
            </div>
            <el-button type="info" icon="el-icon-refresh" size="mini"
                       style="width: 50px; height: 30px; font-size: 12px;padding:3px;margin-top: 2px;margin-left: 2px"
                       @click="resetTime">重置
            </el-button>
          </div>

        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--查看-->
    <el-dialog :title="title" :visible.sync="selectList" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="会议室名称：" prop="broadroomName">
              {{ form.broadroomName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会议室地址：" prop="broadroomAddress">
              {{ form.broadroomAddress }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="可预约时间段：" prop="date">
              {{ form.visitCard }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注：" prop="remark">
              {{ form.remark }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import {
  addBroadroom,
  delBroadroom,
  exportBroadroom,
  getBroadroom,
  listBroadroom,
  updateBroadroom
} from '@/api/server/broadroom/broadroom'
import {addBook, listBook} from "../../../api/server/broadroom/book";
import {parseTime} from "../../../utils/project";
import {listCompany} from "../../../api/server/companies/company";
import {listUser} from "../../../api/system/user";
import {listStaff} from "../../../api/server/companies/staff";

const timeOptions = ['09:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30', '17:00', '17:30', '18:00', '18:30'];
export default {
  name: 'broadroom',
  comments: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //选择日期
      date: undefined,
      //选择开始时间
      changeColor: [],
      startTime: undefined,
      //选择结束时间
      endTime: undefined,
      //日期范围
      dateRange: [],
      // 会议室信息列表
      broadroomList: [],
      //企业下拉框列表
      compOptions: [],
      userOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      //添加或修改
      open: false,
      //预定
      book: false,
      //查看
      selectList: false,
      // 状态数据字典
      statusOptions: [],
      //预定会议室时间段列表
      newTime: [],
      //时间选择列
      timeList: timeOptions,
      //会议室预定记录列表
      broadroomBookList: [],
      //指定会议室预定记录列表
      newList: [],
      //点击时间段数组
      itemList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        broadroomName: undefined,
        broadroomAddress: undefined,
        broadroomStatus: undefined,
        dateRange: [],
      },
      // 表单参数
      form: {},
      //列信息
      columns: [
        {key: 0, label: "序号", visible: true},
        {key: 1, label: "会议室名称", visible: true},
        {key: 2, label: "会议室地址", visible: true},
        {key: 3, label: "会议室人数", visible: true},
        {key: 4, label: "会议室开放状态", visible: true},
        {key: 5, label: "创建时间", visible: true},
      ],
      queryForm: {
        broadroomName: [{pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/, message: '不能为特殊字符', trigger: 'blur'}],
        broadroomAddress: [{pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/, message: '不能为特殊字符', trigger: 'blur'}],
      },
      // 表单校验
      rules: {
        broadroomName: [
          {required: true, message: '会议室名称不能为空', trigger: 'blur'}
        ],
        broadroomAddress: [
          {required: true, message: '会议室地址不能为空', trigger: 'blur'}
        ],
        broadroomNum: [
          {required: true, message: '会议室人数不能为空', trigger: 'blur'}
        ],
        userName: [
          {required: true, message: '联系人不能为空', trigger: 'change'}
        ],
        phoneNumber: [
          {required: true, message: '联系电话不能为空', trigger: 'change'}
        ],
        compName: [
          {required: true, message: '预定企业名称不能为空', trigger: 'change'}
        ],
        date: [
          {required: true, message: '预约时间段不能为空', trigger: 'blur'}
        ],
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('t_broadroom_status').then(response => {
      this.statusOptions = response.data
    })
  },
  methods: {
    /** 查询会议室列表 */
    getList() {
      this.loading = true
      listBroadroom(this.addDateRange1(this.queryParams, this.dateRange)).then(response => {
        this.broadroomList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    //获取点击时间
    getTime(date) {
      this.time = date;
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.broadroomStatus)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.book = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        broadroomName: undefined,
        broadroomAddress: undefined,
        broadroomNum: undefined,
        broadroomStatus: undefined,
        date: undefined,
        startTime: undefined,
        endTime: undefined,
        remark: undefined,
      }
      this.resetForm('form')
    },
    //重置时间段状态
    resetTime() {
      for (let i in this.itemList) {
        this.$refs[this.itemList[i]][0].style.backgroundColor = "rgb(240,241,245)"
        this.$refs[this.itemList[i]][0].style.color = 'rgb(96,98,102)'
        this.$refs[this.itemList[i]][0].style.pointerEvents = 'auto'
      }
      this.itemList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.$refs['queryForm'].validate(valid => {
        if (valid) {
          this.getList()
        }
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.queryParams.params.beginTime = ''
      this.queryParams.params.endTime = ''
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.broadroomId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    //搜索发起请求 传入值为当前select输入的值
    Tolikesearch(query) {
      listCompany({compName: query}).then(res => {
        this.compOptions = res.rows
      })
    },
    //搜索发起请求 传入值为当前select输入的值
    phoneSearch(query) {
      this.userOptions = []
      listUser({phoneNumber: query}).then(res => {
        //遍历
        let tempList = res.rows
        let arr = JSON.parse(JSON.stringify(tempList).replace(/phoneNumber/g, "staffPhone")
          .replace(/deptId/g, 'compId')
          .replace(/deptName/g, 'compName')
          .replace(/dept/g, 'company'))
        for (let i in arr) {
          this.userOptions.push(arr[i])
        }
      })
      listStaff({phoneNumber: query}).then(res => {
        let tempList = res.rows
        let array = JSON.parse(JSON.stringify(tempList).replace(/staffName/g, "userName"))
        for (let i in array) {
          this.userOptions.push(array[i])
        }
      })
    },
    //获取选择的服务人员信息并赋值给form表单中的数据
    changeName(e) {
      for (let i in this.compOptions) {
        if (e === this.compOptions[i].compId) {
          this.form.compId = this.userOptions[i].compId
          this.form.compName = this.userOptions[i].company.compName
          // this.form.phone = this.userOptions[i].staffPhone
          // this.form.userName = this.userOptions[i].userName
        }
      }
    },
    //获取选择的服务人员信息并赋值给form表单中的数据
    changePhone(e) {
      for (let i in this.userOptions) {
        if (e === this.userOptions[i].staffPhone) {
          //this.form.compId = this.userOptions[i].compId
          //this.form.compName = this.userOptions[i].company.compName
          this.form.phone = this.userOptions[i].staffPhone
          this.form.userName = this.userOptions[i].userName
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加会议室信息'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const broadroomId = row.broadroomId || this.broadroomId
      getBroadroom(broadroomId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改会议室信息'

      })
    },
    /** 预约按钮操作 */
    handleUpdateStatus(row) {
      this.reset()
      this.newTime = []
      this.newList = []
      this.itemList = []
      const broadroomId = row.broadroomId || this.broadroomId
      getBroadroom(broadroomId).then(response => {
        this.form = response.data
        this.book = true
        this.title = '预定会议室'
        this.queryParams.broadroomId = broadroomId
        listBook(this.queryParams).then(response => {
          this.broadroomBookList = response.rows
        })
      })
    },
    //选择日期
    selectedDate(date) {
      this.newTime = []
      this.newList = []
      this.itemList = []
      for (let i in this.timeList) {
        this.$refs[this.timeList[i]][0].style.backgroundColor = "rgb(240,241,245)"
        this.$refs[this.timeList[i]][0].style.color = 'rgb(96,98,102)'
        this.$refs[this.timeList[i]][0].style.pointerEvents = 'auto'
      }
      this.date = date
      let newDate = undefined
      //获取指定日期的会议室预约记录
      for (let i in this.broadroomBookList) {
        newDate = this.broadroomBookList[i].bookStart.substring(0, 10)
        if (newDate === this.date) {
          if (this.broadroomBookList[i].approverState == '1') {
            this.newList.push(this.broadroomBookList[i])
          }
        }
      }

      //提取指定日期会议室预约时间段
      for (let i in this.newList) {
        let arr = []
        arr.push((this.newList[i].bookStart.substring(11, 16)))
        arr.push((this.newList[i].bookEnd.substring(11, 16)))
        this.newTime.push(...arr)
      }
      //存放时间段的位置
      let array = []
      for (let i in this.timeList) {
        for (let j in this.newTime) {
          if (this.timeList[i] == this.newTime[j]) {
            array.push(i)
          }
        }
      }
      //更改从开始到结束使用期间的时间样式
      for (let i = 0; i < array.length; i++) {
        if (i % 2 == 0) {
          let start = parseInt(array[i])
          let end = parseInt(array[i + 1])
          for (start; start <= end; start++) {
            this.$refs[this.timeList[start]][0].style.backgroundColor = "rgb(189,209,226)"
            this.$refs[this.timeList[start]][0].style.color = 'white'
            this.$refs[this.timeList[start]][0].style.pointerEvents = 'none'
          }
        }
      }
    },
    //选择时间
    selectTime(item) {
      this.itemList.push(item)
      //判断是否超出两个值
      if (this.itemList.length <= 2) {
        this.$refs[item][0].style.backgroundColor = "rgb(14,144,255)"
        this.$refs[item][0].style.color = 'white'
      } else {
        this.$message("只能选择两个时间！");
      }

    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.book) {
            if (this.itemList.length === 2) {
              let date = this.date
              let startTime = this.itemList[0]
              let endTime = this.itemList[1]
              this.form.bookStart = parseTime(date + " " + startTime)
              this.form.bookEnd = parseTime(date + " " + endTime)
              for (let i in this.compOptions) {
                if (this.compOptions[i].compName == this.form.compName) {
                  this.form.compId = this.compOptions[i].compId
                }
              }
              addBook(this.form).then(response => {
                this.msgSuccess('预约成功')
                this.book = false
                this.getList()
              })
            } else {
              this.msgInfo('请选择具体时间')
            }
          } else if (this.form.broadroomId !== undefined) {
            updateBroadroom(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addBroadroom(this.form).then(response => {
              if (response.data === 0) {
                this.$confirm('该会议室已存在', '提示', {
                  cancelButtonClass: 'btn-custom-cancel',
                  closeOnClickModal: false,
                  type: 'info'
                })
              } else {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    }
    ,
    /** 删除按钮操作 */
    handleDelete(row) {
      const broadroomId = row.broadroomId || this.ids
      if (broadroomId.length === 0) {
        this.$confirm('请选择需要删除的记录')
      } else {
        this.$confirm('是否确认删除该数据项?', '警告', {
          cancelButtonClass: 'btn-custom-cancel',
          closeOnClickModal: false,
          type: 'warning'
        }).then(function () {
          return delBroadroom(broadroomId)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
      }
    }
    ,

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有会议室信息数据项？', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        closeOnClickModal: false,
        type: 'info'
      }).then(function () {
        return exportBroadroom(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    }
  }
}
</script>

<style>
.timesList {
  width: 300px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.times {
  width: 50px;
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 2px;
  background-color: #f0f1f5;
  cursor: pointer;
  border-radius: 5px
}

.times:hover {
  color: rgb(14, 144, 255);
}


</style>
